<?php
namespace api\modules\merchant\controllers\goods;

use api\modules\merchant\models\GoodsCreateForm;
use api\modules\merchant\models\GoodsUpdateForm;
use backend\widgets\provinces\Provinces;
use common\models\goods\Goods;
use yii\data\ActiveDataProvider;
use Yii;
use yii\data\Pagination;
use yii\web\NotFoundHttpException;
use api\controllers\OnAuthController;
use common\enums\StatusEnum;
use common\helpers\ResultDataHelper;
use common\models\store\Store;

/**
 * 商品接口
 *
 * Class InfoController
 * @package api\modules\merchant\controllers\goods
 * @property \yii\db\ActiveRecord $modelClass
 * @author tjj
 */
class InfoController extends OnAuthController
{
    public $modelClass = 'common\models\goods\GoodsCommon';


    /**
     * 商品列表
     * @return ActiveDataProvider
     */
    public function actionIndex()
    {
        $request = Yii::$app->request;
        $keyword = $request->get('keyword')??'';
        $gc_id = $request->get('gc_id')??0;
        $status = $request->get('status')??null;

        $query = $this->modelClass::find()
            ->select(['goods_commonid','goods_name','goods_code','goods_bar','goods_image','goods_unit','gc_id','goods_salenum','created_at','status'])
            ->with(['gclass'])
            ->orderBy('goods_commonid desc')
            ->asArray();

        if(!empty($keyword))
            $query->andWhere(['like','goods_name',$keyword]);

        if(0 < $gc_id)
            $query->andWhere(['gc_id'=>$gc_id]);

        if(!is_null($status) && is_numeric($status))
            $query->andWhere(['status'=>$status]);

        $pages = new Pagination(['totalCount' => $query->count(), 'pageSize' => $this->pageSize]);

        $models = $query->offset($pages->offset)
            ->limit($pages->limit)
            ->all();

        return [
            'models'=>$models,
            'pgages'=>[
                'page'=> intval($request->get('page'))??0,
                'page_size'=> intval($this->pageSize),
                'total_count'=> intval($pages->totalCount),
            ]
        ];
    }

    /**
     * 获取详情
     * @param $id
     * @return array|\yii\db\ActiveRecord|null
     * @throws NotFoundHttpException
     */
    public function actionView($id)
    {
        return $this->getGoods($id);
    }

    /**
     * 上架下架
     * @param $id
     * @return bool|mixed
     * @throws NotFoundHttpException
     */
    public function actionStatus(){
        $id = Yii::$app->request->post('id');
        $status = Yii::$app->request->post('status');

        if(is_array($id)){
//            $model = $this->modelClass::find()->where(['in','goods_commonid',$id]);

            return $this->modelClass::updateAll(['status'=>$status,['in','goods_commonid',$id]]);
        }else{
            $model = $this->modelClass::findOne(['goods_commonid'=>$id]);
            if($model){
                $this->checkStore($model['store_id']);
            }else return ResultDataHelper::api(422, '请求的数据不存在');

            $model->status = $status;
            return $model->save();
        }

    }

    /**
     * 删除
     * @param $id
     * @return bool|mixed
     * @throws NotFoundHttpException
     */
    public function actionDelete($id)
    {
        $model = $this->modelClass::findOne(['goods_commonid'=>$id]);
        if($model){
            $this->checkStore($model['store_id']);
        }else return ResultDataHelper::api(422, '请求的数据不存在');

        $model->status = StatusEnum::DELETE;
        return $model->save();
    }

    /**
     * @param $id
     * @return array|mixed|\yii\db\ActiveRecord|null
     * @throws NotFoundHttpException
     */
    public function actionUpdate($id)
    {
        $model = $this->modelClass::findOne($id);
        if($model){
            $this->checkStore($model['store_id']);
        }else
            return ResultDataHelper::api(422, '请求的数据不存在');

        $model = new GoodsUpdateForm($id);
        $model->attributes = Yii::$app->request->post();

        if ($model->validate())
        {
            if($model->goodsUpdate()){
                return $this->getGoods($id);
            }else
                return ResultDataHelper::api(422, '保存失败');
        }
        return ResultDataHelper::api(422, $model->getFirstError());
    }

    /**
     * 新建商品
     * @return mixed|void|\yii\db\ActiveRecord
     */
    public function actionCreate()
    {
        $store_id = Yii::$app->request->post('store_id')??0;

        if(!$store_id){
            throw new NotFoundHttpException('店铺参数有误.');
        }

        $this->checkStore($store_id);

        $model = new GoodsCreateForm();
        $data = Yii::$app->request->post();
        $data['member_id'] = Yii::$app->user->identity->member_id;
        $data['image_list'] = $data['image_list']??[];
        $data['attr'] = $data['attr']??[];
        $data['goods_list'] = $data['goods_list']??[];
        $data['image_list'] = is_array($data['image_list'])?json_encode($data['image_list']):$data['image_list'];
        $data['attr'] = is_array($data['attr'])?json_encode($data['attr']):$data['attr'];
        $data['goods_list'] = is_array($data['goods_list'])?json_encode($data['goods_list']):$data['goods_list'];

        $model->attributes = $data;

        if ($model->validate())
        {
            if($goods_commonid = $model->goodsCreate())
            {
                return $this->getGoods($goods_commonid);
            }else
                return ResultDataHelper::api(422, '保存失败');
        }
        return ResultDataHelper::api(422, json_encode($model->getErrors()));
    }

    /**
     * 整合商品数据
     * @param $id
     * @throws NotFoundHttpException
     */
    private function getGoods($id){
        $res_model = $this->modelClass::find()
            ->where(['goods_commonid' => $id])
            ->select(['goods_commonid','goods_name', 'goods_code', 'goods_bar', 'gc_id','brand_id', 'goods_unit','goods_price','goods_marketprice','goods_serial','status'])
            ->with(['attr','goods_list','image_list','gclass','brand'])
            ->asArray()
            ->one();

        if (!$res_model)
        {
            throw new NotFoundHttpException('请求的数据不存在或您的权限不足.');
        }
        foreach ($res_model['goods_list'] as &$goods){
            $_attr = [];
            foreach ($goods['attr_index'] as $attr_item){
                $_attr[] = [
                    'attr_id'=>$attr_item['attr_id'],
                    'attr_name'=>$attr_item['attr']['attr_name'],
                    'attr_value_id'=>$attr_item['attr_value_id'],
                    'attr_value_name'=>$attr_item['attr_value']['attr_value_name'],
                ];
            }
            $goods['attr'] = $_attr;
            unset($goods['attr_index']);
        }
        return $res_model;
    }

    /**
     * 权限验证
     *
     * @param string $action 当前的方法
     * @param null $model 当前的模型类
     * @param array $params $_GET变量
     * @throws \yii\web\BadRequestHttpException
     */
    public function checkAccess($action, $model = null, $params = [])
    {
        // 方法名称
//        if (in_array($action, ['delete', 'index']))
//        {
//            throw new \yii\web\BadRequestHttpException('权限不足');
//        }
    }
}
